<template>
  <div class="play-bar" :class="{ show: !toggle }">
    <div class="fold" :class="{ turn: toggle }">
      <yin-icon :icon="iconList.ZHEDIE" @click="toggle = !toggle"></yin-icon>
    </div>
    <!--播放进度-->
    <el-slider class="progress" v-model="nowTime" @change="changeTime" size="small"></el-slider>
    <div class="control-box">
      <div class="info-box">
        <!--歌曲图片-->
        <el-image class="song-bar-img" fit="contain" v-if="songPic" :src="attachImageUrl(songPic)" @click="goPlayerPage"/>
        <!--播放开始结束时间-->
        <div v-if="songId">
          <div class="song-info">{{ songTitle }} - {{ singerName }}</div>
          <div class="time-info">{{ startTime }} / {{ endTime }}</div>
        </div>
      </div>
      <div class="song-ctr">
        <yin-icon class="yin-play-show" :icon="playStateList[playStateIndex]" @click="changePlayState"></yin-icon>
        <!--上一首-->
        <yin-icon class="yin-play-show" :icon="iconList.SHANGYISHOU" @click="prev"></yin-icon>
        <!--播放-->
        <yin-icon :icon="playBtnIcon" @click="togglePlay"></yin-icon>
        <!--下一首-->
        <yin-icon class="yin-play-show" :icon="iconList.XIAYISHOU" @click="next"></yin-icon>
        <!--音量-->
        <el-dropdown class="yin-play-show" trigger="click">
          <yin-icon v-if="volume !== 0" :icon="iconList.YINLIANG"></yin-icon>
          <yin-icon v-else :icon="iconList.JINGYIN"></yin-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-slider class="yin-slider" style="height: 150px; margin: 10px 0" v-model="volume"
                         :vertical="true"></el-slider>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="song-ctr song-edit">
        <!--收藏-->
        <yin-icon
            class="yin-play-show"
            :class="{ active: isCollection }"
            :icon="isCollection ? iconList.like : iconList.dislike"
            @click="changeCollection"
        ></yin-icon>
        <!--下载-->
        <yin-icon
            class="yin-play-show"
            :icon="iconList.download"
            @click="
            downloadMusic({
              songUrl,
              songName: singerName + '-' + songTitle,
            })
          "
        ></yin-icon>
        <!--歌曲列表-->
        <yin-icon :icon="iconList.LIEBIAO" @click="changeAside"></yin-icon>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, getCurrentInstance, onMounted, ref, watch} from "vue";
import {useStore} from "vuex";
import mixin from "@/mixins/mixin";
import YinIcon from "./YinIcon.vue";
import {HttpManager} from "@/api";
import {formatSeconds} from "@/utils";
import {Icon, RouterName} from "@/enums";

// 导入组件
const components = {
  YinIcon,
};

// 获取实例和store
const {proxy} = getCurrentInstance();
const store = useStore();
const {routerManager, playMusic, checkStatus, downloadMusic} = mixin();

// setup中的数据
const isCollection = ref(false); // 是否收藏

// 计算属性 - setup部分
const userIdVO = computed(() => store.getters.userId);
const songIdVO = computed(() => store.getters.songId);
const token = computed(() => store.getters.token);

// setup中的watch
watch(songIdVO, () => {
  initCollection();
});
watch(token, (value) => {
  if (!value) isCollection.value = false;
});

// setup中的异步函数
async function initCollection() {
  if (!checkStatus(false)) return;

  const userId = userIdVO.value;
  const type = '0';
  const songId = songIdVO.value;
  isCollection.value =  ((await HttpManager.isCollection({userId, type, songId})) as ResponseBody).data;
}

async function changeCollection() {
  if (!checkStatus()) return;

  const userId = userIdVO.value;
  const type = '0'; //这里要看看 不能直接写死
  const songId = songIdVO.value;

  const result = isCollection.value? ((await HttpManager.deleteCollection(userIdVO.value, songIdVO.value)) as ResponseBody): ((await HttpManager.setCollection({userId, type, songId})) as ResponseBody);
  (proxy as any).$message({
    message: result.message,
    type: result.type,
  });

  if (result.data == true || result.data == false) isCollection.value = result.data;
}

// setup中的生命周期
onMounted(() => {
  if (songIdVO.value) initCollection();
});

// data中的数据转换为ref
const startTime = ref("00:00");
const endTime = ref("00:00");
const nowTime = ref(0); // 进度条的位置
const toggle = ref(true);
const volume = ref(50);
const playState = ref(Icon.XUNHUAN);
const playStateList = ref([Icon.XUNHUAN, Icon.LUANXU]);
const playStateIndex = ref(0);
const iconList = ref({
  download: Icon.XIAZAI,
  ZHEDIE: Icon.ZHEDIE,
  SHANGYISHOU: Icon.SHANGYISHOU,
  XIAYISHOU: Icon.XIAYISHOU,
  YINLIANG: Icon.YINLIANG1,
  JINGYIN: Icon.JINGYIN,
  LIEBIAO: Icon.LIEBIAO,
  dislike: Icon.Dislike,
  like: Icon.Like,
});

// mapGetters转换为computed
const userId = computed(() => store.getters.userId);
const isPlay = computed(() => store.getters.isPlay); // 播放状态
const playBtnIcon = computed(() => store.getters.playBtnIcon); // 播放状态的图标
const songId = computed(() => store.getters.songId); // 音乐id
const songUrl = computed(() => store.getters.songUrl); // 音乐地址
const songTitle = computed(() => store.getters.songTitle); // 歌名
const singerName = computed(() => store.getters.singerName); // 歌手名
const songPic = computed(() => store.getters.songPic); // 歌曲图片
const curTime = computed(() => store.getters.curTime); // 当前音乐的播放位置
const duration = computed(() => store.getters.duration); // 音乐时长
const currentPlayList = computed(() => store.getters.currentPlayList);
const currentPlayIndex = computed(() => store.getters.currentPlayIndex); // 当前歌曲在歌曲列表的位置
const showAside = computed(() => store.getters.showAside); // 是否显示侧边栏
const autoNext = computed(() => store.getters.autoNext); // 用于触发自动播放下一首

// watch中的监听
watch(isPlay, (value) => {
  store.commit("setPlayBtnIcon", value ? Icon.ZANTING : Icon.BOFANG);
});
watch(volume, () => {
  store.commit("setVolume", volume.value / 100);
});
watch(curTime, () => {
  startTime.value = formatSeconds(curTime.value);
  endTime.value = formatSeconds(duration.value);
  // 移动进度条
  nowTime.value = (curTime.value / duration.value) * 100;
});
watch(autoNext, () => {
  next();
});

// methods中的方法
function changeAside() {
  store.commit("setShowAside", !showAside.value);
}

// 控制音乐播放 / 暂停
function togglePlay() {
  store.commit("setIsPlay", isPlay.value ? false : true);
}

function changeTime() {
  store.commit("setChangeTime", duration.value * (nowTime.value * 0.01));
}

function changePlayState() {
  playStateIndex.value = playStateIndex.value >= playStateList.value.length - 1 ? 0 : ++playStateIndex.value;
  playState.value = playStateList.value[playStateIndex.value];
}

// 上一首
function prev() {
  if (playState.value === Icon.LUANXU) {
    let playIndex = Math.floor(Math.random() * currentPlayList.value.length);
    playIndex = playIndex === currentPlayIndex.value ? playIndex + 1 : playIndex;
    store.commit("setCurrentPlayIndex", playIndex);
    toPlay(currentPlayList.value[playIndex].url);
  } else if (currentPlayIndex.value !== -1 && currentPlayList.value.length > 1) {
    if (currentPlayIndex.value > 0) {
      store.commit("setCurrentPlayIndex", currentPlayIndex.value - 1);
      toPlay(currentPlayList.value[currentPlayIndex.value].url);
    } else {
      store.commit("setCurrentPlayIndex", currentPlayList.value.length - 1);
      toPlay(currentPlayList.value[currentPlayIndex.value].url);
    }
  }
}

// 下一首
function next() {
  if (playState.value === Icon.LUANXU) {
    let playIndex = Math.floor(Math.random() * currentPlayList.value.length);
    playIndex = playIndex === currentPlayIndex.value ? playIndex + 1 : playIndex;
    store.commit("setCurrentPlayIndex", playIndex);
    toPlay(currentPlayList.value[playIndex].url);
  } else if (currentPlayIndex.value !== -1 && currentPlayList.value.length > 1) {
    if (currentPlayIndex.value < currentPlayList.value.length - 1) {
      store.commit("setCurrentPlayIndex", currentPlayIndex.value + 1);
      toPlay(currentPlayList.value[currentPlayIndex.value].url);
    } else {
      store.commit("setCurrentPlayIndex", 0);
      toPlay(currentPlayList.value[0].url);
    }
  }
}

// 选中播放
function toPlay(url) {
  if (url && url !== songUrl.value) {
    const song = currentPlayList.value[currentPlayIndex.value];
    playMusic({
      id: song.id,
      url,
      pic: song.pic,
      index: currentPlayIndex.value,
      name: song.name,
      lyric: song.lyric,
      currentSongList: currentPlayList.value,
    });
  }
}

function goPlayerPage() {
  routerManager(RouterName.Lyric, {path: `${RouterName.Lyric}/${songId.value}`});
}

// 其他工具函数
const attachImageUrl = HttpManager.attachImageUrl;
</script>

<style lang="scss" scoped>
// 使用Sass 3.0新模块系统导入
@use "@/assets/css/yin-play-bar.scss";
</style>
